package com.xy.modular.basics.action;

import com.xy.framework.base.controller.BaseController;
import com.xy.framework.mreturn.MReturnObject;
import com.xy.framework.pager.PageRequest;
import com.xy.framework.pager.SearchCondition;
import com.xy.framework.util.uuid.UUIDUtils;
import com.xy.modular.basics.entity.House;
import com.xy.modular.basics.service.IHouseService;
import com.xy.modular.sys.action.ModuleController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/house")
public class HouseController extends BaseController {
	static Logger log = LoggerFactory.getLogger(ModuleController.class);

	@Resource
	private IHouseService houseService;

	@RequestMapping(value = "/select/list", method = RequestMethod.GET)
	public @ResponseBody MReturnObject list(House house, HttpServletRequest request) {
		PageRequest pageRequest = newPageRequest(request);
		pageRequest.addAndCondition(House.PARENT, SearchCondition.EQUAL, house.getId());
		pageRequest.addSortConditions(House.NAME, SearchCondition.CONVERT_ASC);
		return new MReturnObject(MReturnObject.SUCCESS, houseService.findAll(pageRequest));
	}

	@RequestMapping(value = "/select/save/{block}/{flock}/{unit}/{door}/{layer}")
	public @ResponseBody MReturnObject list(@PathVariable("block") String block, @PathVariable("flock") String flock,
			@PathVariable("unit") String unit, @PathVariable("door") String door, @PathVariable("layer") String layer,
			HttpServletRequest request) {
		House house = houseService.getByName(block);
		if (houseService.getByName(block) == null) {// 小区
			house = new House(UUIDUtils.UUID(), "0", block);
			houseService.save(house);
		}

		if (houseService.getByName(flock) == null) {// 幢
			house = new House(UUIDUtils.UUID(), house.getId(), flock);
			houseService.save(house);
		}

		house.setParent(house.getId());
		for (int j = 1; j < Integer.parseInt(unit); j++) {
			for (int i = 1; i <= Integer.parseInt(door); i++) {
				for (int a = 1; a <= Integer.parseInt(layer); a++) {
					house.setId(UUIDUtils.UUID());
					house.setName((j < 10 ? "0" + j : j) + "单元" + (i < 10 ? "0" + i : i) + (a < 10 ? "0" + a : a));
					houseService.save(house);
					System.out.println((j < 10 ? "0" + j : j) + "单元" + (i < 10 ? "0" + i : i) + (a < 10 ? "0" + a : a));
				}
			}
		}
		return null;
	}
}
